package com.sitech.ibnms.util.charts.fusion.column;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.sitech.ibnms.util.charts.domain.CURR_DATA_DOMAIN;
import com.sitech.ibnms.util.charts.fusion.FusionChartCommon;

/**
 * @author Mirror_Jean
 *
 * @Date :Jan 7, 2011
 * @Time :3:58:46 PM
 * @Vesion :FusionColumnChart
 */
public class FusionColumnChart {

	public String getColumnChart(FusionColumnChartParameter parameter,
			List<CURR_DATA_DOMAIN> hisData) {
		
		return  FusionChartCommon.getScript(parameter).replaceAll("######", 
				this.setLineChartParameter(parameter, hisData).toString());
	}
	
	public String setLineChartParameter(FusionColumnChartParameter parameter,
			List<CURR_DATA_DOMAIN> hisData){
		Document document = DocumentHelper.createDocument();
		Element chartHead = document.addElement("chart");
		String[] paramName = FusionColumnChartParamName.paramName;
		String paramValue[] = FusionColumnChartParameter.getParamVaule(parameter, paramName);
		int idx = 0;
		for (String name : paramName) {
			chartHead.addAttribute(name, paramValue[idx]);
			idx++;
		}
		setChildParam(chartHead, "set", parseResult(hisData));
		return formatXMLData(document);
	}
	
	private void setChildParam(Element parent, String childName,
			HashMap<String,String> childDataMap) {
		try {
			int i = 0;
			if (childDataMap != null){
				Set<String> key = childDataMap.keySet();
				Iterator<String> it = key.iterator();
				while (it.hasNext()) {
					Element chartNode = parent.addElement(childName);
					String name = it.next();
					String value = childDataMap.get(name);
					chartNode.addAttribute("label", name);
					chartNode.addAttribute("value", value);
				}
			}
		} catch (Exception ex) {
			System.out.println("add child chart node has exception ,method : setChildParam();");
			ex.printStackTrace();
		}
	}
	
	private String formatXMLData(Document document) {
		String xml[] = document.asXML().split("\n");
		return xml[1].replace("\"", "\'");
	}
	
	
	public HashMap<String,String> parseResult(List<CURR_DATA_DOMAIN> hisData){
		List<CURR_DATA_DOMAIN> valueDomain = hisData;
		HashMap<String,String> resultMap = new HashMap<String,String>();
		for(CURR_DATA_DOMAIN names : hisData){
			//�ж��Ƿ�Ϊ�ļ���
			String kpi_id = names.getKPI_ID();
			if(kpi_id != null && kpi_id.equals("CM-00-03-003-01")){
				String nUnitID = names.getUNIT_ID();
				for(CURR_DATA_DOMAIN values : valueDomain){
					kpi_id = values.getKPI_ID();
					String vUnitID = values.getUNIT_ID();
					if(kpi_id != null && kpi_id.equals("PM-00-03-004-01") && nUnitID.equals(vUnitID)){
						resultMap.put(names.getKPI_VALUE(), values.getKPI_VALUE().replaceAll("%", ""));
						break;
					}
				}
			}
		}
		return resultMap;
		
	}
}
